package top.canyue.word_range.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import top.canyue.word_range.exception.TokenException;
import top.canyue.word_range.pojo.dto.LoginUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工厂
 * @author canyue
 * @version 1.1 2024/06/26
 */

@Component
@Data
public class JwtUtil {
    private String SECRET = "CanyueCanyue";  //随机盐
    // TODO: 这里注入配置文件中的值失败
    private int expiration = 43200;


    //根据用户ID生成token
    public String createToken(LoginUser loginUser) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("subject", loginUser.getUser().getId());
        claims.put("createTime", new Date());
        return createToken(claims);
    }

    public String createToken(String userId) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("subject", userId);
        claims.put("createTime", new Date());
        return createToken(claims);
    }

    //解析JWT
    public Claims parseJWT(String token) {
        try {
            return getClaimsFromToken(token);
        } catch (Exception e) {
            throw new TokenException("Token非法",token);
        }
    }

    //根据token获取用户名
    public String getUserIdFromToken(String token) {
        String userId = "";
        Claims claims = parseJWT(token);
        if (claims != null) {
            userId = claims.get("subject").toString();
        }
        return userId;
    }

    //从token中获取荷载
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    //生成jwt
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expirationDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    //生成token失效时间
    private Date expirationDate() {
        long l = System.currentTimeMillis() ;
        return new Date(l + expiration * 1000L);
    }

    //判断token是否有效
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserIdFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    //判断token、是否失效
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFeomToken(token);
        return expiredDate.before(new Date());
    }

    //从荷载中获取时间
    private Date getExpiredDateFeomToken(String token) {
        try{
            Claims claims = getClaimsFromToken(token);
            return claims.getExpiration();
        }catch (Exception e){
            throw new TokenException("Token非法",token);
        }
    }

    //判断token是否可以被刷新
    public boolean canBeRefreshed(String token) {
        return !isTokenExpired(token);
    }

    //刷新token
    public String refreshToken(String token) {
        try{
            Claims claims = getClaimsFromToken(token);
            //修改为当前时间
            claims.put("createTime", new Date());
            return createToken(claims);
        }catch (Exception e){
            throw new TokenException("Token非法",token);
        }
    }
}
